package com.example.util;

import lombok.extern.slf4j.Slf4j;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HWDiskStore;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;

import java.io.File;
import java.util.List;

/**
 * 系统监控工具类 - 使用OSHI库
 */
@Slf4j
public class SystemMonitorUtil {

    private static final SystemInfo SYSTEM_INFO = new SystemInfo();

    /**
     * 获取CPU使用率
     *
     * @return CPU使用率（百分比）
     */
    public static double getCpuUsage() {
        CentralProcessor processor = SYSTEM_INFO.getHardware().getProcessor();
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            log.error("获取CPU使用率时被中断", e);
        }
        
        return processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100;
    }

    /**
     * 获取内存使用率
     *
     * @return 内存使用率（百分比）
     */
    public static double getMemoryUsage() {
        GlobalMemory memory = SYSTEM_INFO.getHardware().getMemory();
        return 100.0 * (memory.getTotal() - memory.getAvailable()) / memory.getTotal();
    }

    /**
     * 获取磁盘使用率
     *
     * @param path 磁盘路径，例如"/"或"C:"
     * @return 磁盘使用率（百分比）
     */
    public static double getDiskUsage(String path) {
        // 方法1：通过Java File API获取磁盘使用率
        File file = new File(path);
        if (file.exists()) {
            long totalSpace = file.getTotalSpace();
            long freeSpace = file.getFreeSpace();
            
            if (totalSpace > 0) {
                return 100.0 * (totalSpace - freeSpace) / totalSpace;
            }
        }
        
        // 方法2：通过OSHI获取磁盘使用率
        try {
            FileSystem fileSystem = SYSTEM_INFO.getOperatingSystem().getFileSystem();
            List<OSFileStore> fileStores = fileSystem.getFileStores();
            
            for (OSFileStore store : fileStores) {
                if (store.getMount().startsWith(path)) {
                    long total = store.getTotalSpace();
                    long free = store.getFreeSpace();
                    
                    if (total > 0) {
                        return 100.0 * (total - free) / total;
                    }
                }
            }
        } catch (Exception e) {
            log.error("通过OSHI获取磁盘使用率失败", e);
        }
        
        // 方法3：通过OSHI硬件信息获取磁盘活动
        try {
            List<HWDiskStore> diskStores = SYSTEM_INFO.getHardware().getDiskStores();
            if (!diskStores.isEmpty()) {
                HWDiskStore diskStore = diskStores.get(0);
                long reads = diskStore.getReads();
                long writes = diskStore.getWrites();
                long total = reads + writes;
                
                if (total > 0) {
                    return 100.0 * writes / total; // 使用写入比例作为估计值
                }
            }
        } catch (Exception e) {
            log.error("通过OSHI获取磁盘活动失败", e);
        }
        
        return 0.0;
    }
} 